/**
 * 时间戳转 yyyy-MM-dd HH:mm:ss
 * @param {number} timestamp - 时间戳，支持秒或毫秒
 * @returns {string} 格式化后的时间
 */
export function formatTimestamp(timestamp) {
  // 如果是秒级时间戳，转成毫秒
  if (String(timestamp).length === 10) {
    timestamp = timestamp * 1000
  }
  
  const date = new Date(timestamp)

  const Y = date.getFullYear()
  const M = String(date.getMonth() + 1).padStart(2, '0')
  const D = String(date.getDate()).padStart(2, '0')
  const h = String(date.getHours()).padStart(2, '0')
  const m = String(date.getMinutes()).padStart(2, '0')
  const s = String(date.getSeconds()).padStart(2, '0')

  return `${Y}-${M}-${D} ${h}:${m}:${s}`
}

/**
 * 将数值转为汉字大写
 * @param {*} num 
 * @returns 
 */
export function numberToChinese(num) {
  const digit = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
  const unit = ["", "拾", "佰", "仟"];
  const sectionUnit = ["", "万", "亿", "兆"];
  const decimalUnit = ["角", "分"];

  if (num === 0 || num === "0") return "零元整";
  num = parseFloat(num);
  if (isNaN(num)) return "";

  let [integer, decimal] = num.toString().split(".");
  let result = "";

  // 整数部分
  if (parseInt(integer, 10) > 0) {
    let integerStr = "";
    let sectionCount = 0;

    while (integer.length > 0) {
      let section = integer.slice(-4);
      integer = integer.slice(0, -4);

      let sectionStr = sectionToChinese(section, digit, unit);
      if (sectionStr) {
        integerStr = sectionStr + sectionUnit[sectionCount] + integerStr;
      }
      sectionCount++;
    }
    result += integerStr + "元";
  }

  // 小数部分
  if (decimal) {
    let decimalStr = "";
    for (let i = 0; i < decimalUnit.length; i++) {
      if (decimal[i]) {
        let n = decimal[i];
        if (n !== "0") {
          decimalStr += digit[n] + decimalUnit[i];
        }
      }
    }
    result += decimalStr;
  }

  // 没有小数部分，加 “整”
  if (!decimal || decimal === "0" || /^0+$/.test(decimal)) {
    result += "整";
  }

  return result;
}

// 处理四位数以内的整数
function sectionToChinese(section, digit, unit) {
  section = parseInt(section, 10);
  if (section === 0) return "";

  let str = "";
  let unitPos = 0;
  let zero = true;

  while (section > 0) {
    let d = section % 10;
    if (d === 0) {
      if (!zero) {
        zero = true;
        str = digit[d] + str;
      }
    } else {
      zero = false;
      str = digit[d] + unit[unitPos] + str;
    }
    unitPos++;
    section = Math.floor(section / 10);
  }
  return str.replace(/零+$/g, ""); // 去掉末尾多余的零
}
